/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.templet.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JaxbMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.ColorUtils;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.publish.service.EleTempletPublishService;
import com.thinkgem.jeesite.modules.source.entity.EleSource;
import com.thinkgem.jeesite.modules.source.entity.EleSourceGroup;
import com.thinkgem.jeesite.modules.source.entity.EleSourceMultimedia;
import com.thinkgem.jeesite.modules.source.entity.alarm.EleSourceAlarm;
import com.thinkgem.jeesite.modules.source.entity.alarm.EleSourceAlarmGroup;
import com.thinkgem.jeesite.modules.source.entity.background.EleSourceBackground;
import com.thinkgem.jeesite.modules.source.entity.direction.EleSourceDirection;
import com.thinkgem.jeesite.modules.source.entity.direction.EleSourceDirectionGroup;
import com.thinkgem.jeesite.modules.source.entity.floor.EleSourceFloor;
import com.thinkgem.jeesite.modules.source.entity.floor.EleSourceFloored;
import com.thinkgem.jeesite.modules.source.entity.floor.Floor;
import com.thinkgem.jeesite.modules.source.entity.floor.FloorNode;
import com.thinkgem.jeesite.modules.source.entity.font.EleSourceFont;
import com.thinkgem.jeesite.modules.source.entity.image.EleSourceImage;
import com.thinkgem.jeesite.modules.source.entity.image.EleSourceImageGroup;
import com.thinkgem.jeesite.modules.source.entity.logo.EleSourceLogo;
import com.thinkgem.jeesite.modules.source.entity.program.EleSourceProgram;
import com.thinkgem.jeesite.modules.source.entity.subtitle.EleSourceSubtitle;
import com.thinkgem.jeesite.modules.source.entity.subtitle.EleSourceSubtitleGroup;
import com.thinkgem.jeesite.modules.source.entity.time.EleSourceDate;
import com.thinkgem.jeesite.modules.source.entity.time.EleSourceTime;
import com.thinkgem.jeesite.modules.source.entity.title.EleSourceTitle;
import com.thinkgem.jeesite.modules.source.entity.video.EleSourceVideo;
import com.thinkgem.jeesite.modules.source.entity.video.EleSourceVideoGroup;
import com.thinkgem.jeesite.modules.source.entity.weather.EleSourceWeather;
import com.thinkgem.jeesite.modules.source.entity.week.EleSourceWeek;
import com.thinkgem.jeesite.modules.source.service.EleSourceGroupService;
import com.thinkgem.jeesite.modules.source.service.EleSourceMultimediaService;
import com.thinkgem.jeesite.modules.source.service.alarm.EleSourceAlarmGroupService;
import com.thinkgem.jeesite.modules.source.service.direction.EleSourceDirectionGroupService;
import com.thinkgem.jeesite.modules.source.service.floor.EleSourceFloorService;
import com.thinkgem.jeesite.modules.source.service.floor.EleSourceFlooredService;
import com.thinkgem.jeesite.modules.source.service.floor.FloorNodeService;
import com.thinkgem.jeesite.modules.source.service.font.EleSourceFontService;
import com.thinkgem.jeesite.modules.source.service.image.EleSourceImageGroupService;
import com.thinkgem.jeesite.modules.source.service.logo.EleSourceLogoService;
import com.thinkgem.jeesite.modules.source.service.program.EleSourceProgramService;
import com.thinkgem.jeesite.modules.source.service.subtitle.EleSourceSubtitleGroupService;
import com.thinkgem.jeesite.modules.source.service.time.EleSourceDateService;
import com.thinkgem.jeesite.modules.source.service.time.EleSourceTimeService;
import com.thinkgem.jeesite.modules.source.service.title.EleSourceTitleService;
import com.thinkgem.jeesite.modules.source.service.video.EleSourceVideoGroupService;
import com.thinkgem.jeesite.modules.source.service.weather.EleSourceWeatherService;
import com.thinkgem.jeesite.modules.source.service.week.EleSourceWeekService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.templet.dao.EleTempletDao;
import com.thinkgem.jeesite.modules.templet.dao.EleTempletSourceDao;
import com.thinkgem.jeesite.modules.templet.entity.EleTemplet;
import com.thinkgem.jeesite.modules.templet.entity.EleTempletSource;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.json.XML;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * 模板管理Service
 * @author ZC
 * @version 2017-04-27
 */
@Service
@Transactional(readOnly = false)
public class EleTempletService extends CrudService<EleTempletDao, EleTemplet> {

	@Autowired
	private EleTempletSourceDao eleTempletSourceDao;
	@Autowired
	private EleSourceDirectionGroupService eleSourceDirectionGroupService;
	@Autowired
	private EleSourceAlarmGroupService eleSourceAlarmGroupService;
	@Autowired	
	private EleSourceDateService eleSourceDateService;
	@Autowired
	private EleSourceTimeService eleSourceTimeService;
	@Autowired
	private EleSourceGroupService eleSourceGroupService;	
	@Autowired
	private EleSourceWeatherService eleSourceWeatherService;
	@Autowired
	private EleSourceLogoService eleSourceLogoService;
	@Autowired
	private EleSourceWeekService eleSourceWeekService;
	@Autowired
	private EleSourceFloorService eleSourceFloorService;
	@Autowired
	private EleSourceFlooredService eleSourceFlooredService;
	@Autowired
	private EleSourceFontService eleSourceFontService;
	@Autowired
	private FloorNodeService floorNodeService;
	
	@Autowired
	private EleSourceMultimediaService eleSourceMultimediaService;
    @Autowired
 	private EleSourceImageGroupService eleSourceImageGroupService;
	@Autowired
	private EleSourceVideoGroupService eleSourceVideoGroupService;
	@Autowired
	private EleSourceSubtitleGroupService eleSourceSubtitleGroupService;
	@Autowired
	private EleSourceTitleService eleSourceTitleService;
	
	@Autowired
	private EleTempletPublishService eleTempletPublishService;
	@Autowired
	private EleSourceProgramService eleSourceProgramService;
	
	public EleTemplet get(String id) {
		EleTemplet eleTemplet = super.get(id);
		eleTemplet.setEleTempletSourceList(eleTempletSourceDao.findList(new EleTempletSource(eleTemplet)));
		return eleTemplet;
	}
	
	public List<EleTemplet> findList(EleTemplet eleTemplet) {
		return super.findList(eleTemplet);
	}
	
	public Page<EleTemplet> findPage(Page<EleTemplet> page, EleTemplet eleTemplet) {
		return super.findPage(page, eleTemplet);
	}

	@Transactional(readOnly = false)
	public void save(EleTemplet eleTemplet, String type) {
        try{
            super.save(eleTemplet);
            for (EleTempletSource eleTempletSource : eleTemplet.getEleTempletSourceList()){
                if (eleTempletSource.getId() == null){
                    continue;
                }
                if((EleTempletSource.DEL_FLAG_NORMAL.equals(eleTempletSource.getDelFlag())
                        || EleTempletSource.DEL_FLAG_AUDIT.equals(eleTempletSource.getDelFlag()))
                        && StringUtils.isNotEmpty(eleTempletSource.getSourceType())){
                    if (StringUtils.isBlank(eleTempletSource.getId())){
                        eleTempletSource.setTemplet(eleTemplet);
                        eleTempletSource.preInsert();
                        eleTempletSourceDao.insert(eleTempletSource);
                    }else{
                        eleTempletSource.preUpdate();
                        eleTempletSourceDao.update(eleTempletSource);
                    }
                }else{
                    if (StringUtils.isNotEmpty(eleTempletSource.getId())){
                        eleTempletSourceDao.delete(eleTempletSource);
                    }
                }
            }
		}
		catch(RuntimeException e){
			logger.error("保存模板失败!", e);
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(EleTemplet eleTemplet) {
		super.delete(eleTemplet);
		eleTempletSourceDao.delete(new EleTempletSource(eleTemplet));
	}

    public EleTemplet getbyTempleteByCode(String code){
        EleTemplet eleTemplet = dao.getbyTempleteByCode(code);
        if(null != eleTemplet){
            eleTemplet.setEleTempletSourceList(eleTempletSourceDao.findList(new EleTempletSource(eleTemplet)));
        }
        return eleTemplet;
    }
    public EleTemplet getbyTempleteByName(String name){
        EleTemplet eleTemplet = dao.getbyTempleteByName(name);
        return eleTemplet;
    }
    public boolean createTemplateFile(EleTemplet eleTemplet,String basePath) throws IOException {
    	List<EleTempletSource> templetSourceList = eleTemplet.getEleTempletSourceList();
		String filePath = basePath.substring(0,basePath.lastIndexOf("\\elevator\\"))+"/";//basePath.replace("\\elevator\\","");
		String encoding = "UTF-8";

		Map<String,List<File>> fileMap = new HashMap<>();
		for(EleTempletSource ets:templetSourceList){
			String type = ets.getSourceType();
			String delFlag = ets.getDelFlag();
			if(type == null || "1".equals(delFlag)){
				continue;
			}
			List<File> files = new ArrayList<File>();
			if(type.equals("floored")){
				//ets.setSourceType("registerfloor ");
				type = "registerfloor";
			}
			String configName = type+".xml";
			File config = null;
			String configContent = "";
			switch(type){
			case "multimedia":
				EleSourceMultimedia eleSourceMultimedia = eleSourceMultimediaService.get(ets.getResourceId());
				if(eleSourceMultimedia == null){
					break;
				}
				String videoId = eleSourceMultimedia.getVideoId();
				String imageId = eleSourceMultimedia.getImageId();
				if (!StringUtils.isEmpty(videoId)) {
					EleSourceVideoGroup esvg = eleSourceVideoGroupService.get(videoId);
					List<EleSourceVideo> esvList = esvg.getEleSourceVideoList();
					for (EleSourceVideo esv : esvList) {
						if(!StringUtils.isEmpty(esv.getPath())){
						System.out.println(esv.getPath());
						File esvFile = new File(filePath + esv.getPath());
						files.add(esvFile);
//						String path = esv.getPath();
//						path = path.substring(path.lastIndexOf("/") + 1, path.length());
						esv.setPath(esvFile.getName());
						}
					}
					eleSourceMultimedia.setVideoGroup(esvg);
				}
				if (!StringUtils.isEmpty(imageId)) {
					EleSourceImageGroup esig = eleSourceImageGroupService.get(imageId);
					List<EleSourceImage> esiList = esig.getEleSourceImageList();
					for (EleSourceImage esi : esiList) {
						if(!StringUtils.isEmpty(esi.getPath())){
						File esiFile = new File(filePath + esi.getPath());
						files.add(esiFile);
//						String path = esi.getPath();
//						path = path.substring(path.lastIndexOf("/") + 1, path.length());
						esi.setPath(esiFile.getName());
						}
					}
					eleSourceMultimedia.setImageGroup(esig);
				}
				configContent = JaxbMapper.toXml(eleSourceMultimedia, encoding);
				config = new File(configName);
				FileUtils.writeStringToFile(config, configContent,encoding, false);
				files.add(config);
				break;
			case "title":
				EleSourceTitle est = eleSourceTitleService.get(ets.getResourceId());
				if(est == null){
					break;
				}
				est.setBgcolor(est.getBgcolor().replace("#", ""));
				est.setFgcolor(ColorUtils.rgba2rgb(est.getFgcolor()));
				configContent = JaxbMapper.toXml(est, encoding);
				config = new File(configName);
				FileUtils.writeStringToFile(config, configContent,encoding, false);
				files.add(config);
				break;
			case "sub":
				EleSourceSubtitleGroup essg = eleSourceSubtitleGroupService.get(ets.getResourceId());
				if(essg == null){
					break;
				}
				if(!StringUtils.isEmpty(essg.getBgimage())){
					File essgFile = new File(filePath + essg.getBgimage());
					files.add(essgFile);
//					String image = essg.getBgimage();
//					image = image.substring(image.lastIndexOf("/")+1, image.length());
					essg.setBgimage(essgFile.getName());
				}
				essg.setBgcolor(essg.getBgcolor().replace("#", ""));
				essg.setFgcolor(ColorUtils.rgba2rgb(essg.getFgcolor()));
				configContent = JaxbMapper.toXml(essg, encoding);
				config = new File(configName);
				FileUtils.writeStringToFile(config, configContent,encoding, false);
				files.add(config);
				break;
			case "direction":
				EleSourceDirectionGroup esdg = eleSourceDirectionGroupService.get(ets.getResourceId());
				if(!StringUtils.isEmpty(esdg.getDoublestop())){
					File doublestopFile = new File(filePath + esdg.getDoublestop());

					files.add(doublestopFile);
					String doublestop = esdg.getDoublestop();
					doublestop = doublestop.substring(doublestop.lastIndexOf("/")+1, doublestop.length());
					esdg.setDoublestop(doublestopFile.getName());
				}
				if(!StringUtils.isEmpty(esdg.getStop())){
					File stopFile = new File(filePath + esdg.getStop());

					files.add(stopFile);
					String stop = esdg.getStop();
					stop = stop.substring(stop.lastIndexOf("/")+1, stop.length());
					esdg.setStop(stopFile.getName());
				}
				if(!StringUtils.isEmpty(esdg.getUptips())){
					File upFile = new File(filePath+esdg.getUptips());

					files.add(upFile);
					String uptips = esdg.getUptips();
					uptips = uptips.substring(uptips.lastIndexOf("/")+1, uptips.length());
					esdg.setUptips(upFile.getName());
				}
				if(!StringUtils.isEmpty(esdg.getUpstop())){
					File upstopFile = new File(filePath + esdg.getUpstop());

					files.add(upstopFile);
					String upstop = esdg.getUpstop();
					upstop = upstop.substring(upstop.lastIndexOf("/")+1, upstop.length());
					esdg.setUpstop(upstopFile.getName());
				}
				if(!StringUtils.isEmpty(esdg.getDeftips())){
					File defFile = new File(filePath+esdg.getDeftips());

					files.add(defFile);
					String deftips = esdg.getDeftips();
					deftips = deftips.substring(deftips.lastIndexOf("/")+1, deftips.length());
					esdg.setDeftips(defFile.getName());
				}
				if(!StringUtils.isEmpty(esdg.getDownstop())){
					File downFile = new File(filePath+esdg.getDownstop());

					files.add(downFile);
					String downstop = esdg.getDownstop();
					downstop = downstop.substring(downstop.lastIndexOf("/")+1, downstop.length());
					esdg.setDownstop(downFile.getName());
				}
				if(!StringUtils.isEmpty(esdg.getDowntips())){
					File downTipsFile = new File(filePath+esdg.getDowntips());

					files.add(downTipsFile);
					String downtips = esdg.getDowntips();
					downtips = downtips.substring(downtips.lastIndexOf("/")+1, downtips.length());
					esdg.setDowntips(downTipsFile.getName());
				}
				for (EleSourceDirection ed : esdg.getEleSourceDirectionList()) {
					if (!StringUtils.isEmpty(ed.getNode())) {
						File nodeFile = new File(filePath + ed.getNode());
						files.add(nodeFile);
						String node = ed.getNode();
						node = node.substring(node.lastIndexOf("/") + 1, node.length());
						ed.setNode(nodeFile.getName());
					}
				}
				esdg.devide();
				configContent = JaxbMapper.toXml(esdg, encoding);
				config = new File(configName);
				FileUtils.writeStringToFile(config, configContent,encoding, false);
				files.add(config);
				break;
			case "alarm":
				EleSourceAlarmGroup esag = eleSourceAlarmGroupService.get(ets.getResourceId());
				List<EleSourceAlarm> eaList = esag.getEleSourceAlarmList();
				if(!StringUtils.isEmpty(esag.getDefaudio())){
					File defAutdioFile = new File(filePath+esag.getDefaudio());

					files.add(defAutdioFile);
					
					String def = esag.getDefaudio();
					def = def.substring(def.lastIndexOf("/")+1, def.length());
					esag.setDefaudio(defAutdioFile.getName());
				}
				for(EleSourceAlarm ea:eaList){
					if(!StringUtils.isEmpty(ea.getVolume())){
						File volFile = new File(filePath+ea.getVolume());
						files.add(volFile);
						ea.setVolume(volFile.getName());
					}
					if(!StringUtils.isEmpty(ea.getImage())){
						File imageFile = new File(filePath+ea.getImage());
						files.add(imageFile);
						ea.setImage(imageFile.getName());
					}
					if(!StringUtils.isEmpty(ea.getImageCn())){
						File imageCnFile = new File(filePath+ea.getImageCn());
						files.add(imageCnFile);
						ea.setImageCn(imageCnFile.getName());
					}
					
				}
				configContent = JaxbMapper.toXml(esag, encoding);
				config = new File(configName);
				FileUtils.writeStringToFile(config, configContent,encoding, false);
				files.add(config);
				break;
			case "date":
				EleSourceDate esd = eleSourceDateService.get(ets.getResourceId());
				esd.setFgcolor(ColorUtils.rgba2rgb(esd.getFgcolor()));
				esd.setBgcolor(esd.getBgcolor().replace("#",""));
				configContent = JaxbMapper.toXml(esd, encoding);
				config = new File(configName);
				FileUtils.writeStringToFile(config, configContent,encoding, false);
				files.add(config);
				break;
			case "time":
				EleSourceTime estime = eleSourceTimeService.get(ets.getResourceId());
				estime.setFgcolor(ColorUtils.rgba2rgb(estime.getFgcolor()));
				estime.setBgcolor(estime.getBgcolor().replace("#",""));

				configContent = JaxbMapper.toXml(estime, encoding);
				config = new File(configName);
				FileUtils.writeStringToFile(config, configContent,encoding, false);
				files.add(config);
				break;
			case "weather":
				EleSourceWeather esw = eleSourceWeatherService.get(ets.getResourceId());
				esw.setFgcolor(ColorUtils.rgba2rgb(esw.getFgcolor()));
				esw.setBgcolor(esw.getBgcolor().replace("#",""));

				configContent = JaxbMapper.toXml(esw, encoding);
				config = new File(configName);
				System.out.println(config.getAbsolutePath());
				FileUtils.writeStringToFile(config, configContent,encoding, false);
				files.add(config);
				break;
			case "logo":
				EleSourceLogo logo = eleSourceLogoService.get(ets.getResourceId());							
				String logoPath = logo.getPath();
				if(!StringUtils.isEmpty(logoPath)){
					File logoFile = new File(filePath+logo.getPath());
					files.add(logoFile);
					logoPath = logoPath.substring(logoPath.lastIndexOf("/")+1, logoPath.length());
					logo.setPath(logoFile.getName());
				}
				configContent = JaxbMapper.toXml(logo, encoding);
				config = new File(configName);
				System.out.println(config.getAbsolutePath());
				FileUtils.writeStringToFile(config, configContent,encoding, false);
				files.add(config);
				break;
			case "week":
				EleSourceWeek esweek = eleSourceWeekService.get(ets.getResourceId());
				esweek.setFgcolor(ColorUtils.rgba2rgb(esweek.getFgcolor()));
				esweek.setBgcolor(esweek.getBgcolor().replace("#",""));

				configContent = JaxbMapper.toXml(esweek, encoding);
				config = new File(configName);
				FileUtils.writeStringToFile(config, configContent,encoding, false);
				files.add(config);
				break;
			case "floor":
				EleSourceFloor esfloor = eleSourceFloorService.get(ets.getResourceId());
				esfloor.setFloornodes(floorNodeService.getByGroupId(esfloor.getId()));
				if(!StringUtils.isEmpty(esfloor.getVolumeSelect())){
					File volumeFile = new File(filePath+esfloor.getVolumeSelect());
					files.add(volumeFile);
					String volume = esfloor.getVolumeSelect();
					volume = volume.substring(volume.lastIndexOf("/")+1, volume.length());
					esfloor.setVolumeSelect(volumeFile.getName());
				}
				for(FloorNode f:esfloor.getFloornodes()){
					if(!StringUtils.isEmpty(f.getFloorimg())){
						String image = f.getFloorimg();
						File imageFile = new File(filePath+f.getFloorimg());

						files.add(imageFile);
						image = image.substring(image.lastIndexOf("/")+1, image.length());
						f.setFloorimg(imageFile.getName());
					}
				}
				for(Floor f:esfloor.getFloors()){
					if(!StringUtils.isEmpty(f.getVolumeCn())){
						String volume = f.getVolumeCn();
						File volumeFile = new File(filePath+f.getVolumeCn());

						files.add(volumeFile);
						volume = volume.substring(volume.lastIndexOf("/")+1, volume.length());
						f.setVolumeCn(volumeFile.getName());;
					}
					if(!StringUtils.isEmpty(f.getVolumeEn())){
						String volume = f.getVolumeEn();
						File volumeFile = new File(filePath+f.getVolumeEn());

						files.add(volumeFile);
						volume = volume.substring(volume.lastIndexOf("/")+1, volume.length());
						f.setVolumeEn(volumeFile.getName());
					}
				}
				configContent = JaxbMapper.toXml(esfloor, encoding).replaceAll("<floorimg>","").replaceAll("</floorimg>","");
				config = new File(configName);
				FileUtils.writeStringToFile(config, configContent,encoding, false);
				files.add(config);
				break;
			case "floored":
			case "registerfloor":
				EleSourceFloored esfloored = eleSourceFlooredService.get(ets.getResourceId());
				esfloored.setFgcolor(ColorUtils.rgba2rgb(esfloored.getFgcolor()));
				esfloored.setBgcolor(esfloored.getBgcolor().replace("#",""));
				configContent = JaxbMapper.toXml(esfloored, encoding);
				config = new File(configName);
				FileUtils.writeStringToFile(config, configContent,encoding, false);
				files.add(config);
				break;
			default:
				break;
			}
			fileMap.put(type, files);
			System.out.println(configContent);
		}
		
		//单独处理模板背景
		List<File> bgFiles = new ArrayList<File>();
		String configName = "background.xml";
		File bgConfig = null;
		String bgConfigContent = "";
		
		EleTempletSource bgSource = new EleTempletSource();
		bgSource.setCfgfile(configName);
		bgSource.setRespath("background");
		bgSource.setXloc("0");
		bgSource.setYloc("0");
		bgSource.setWidth(eleTemplet.getWidth()+"");
		bgSource.setHeight(eleTemplet.getHeight()+"");
		bgSource.setSourceType("background");
		eleTemplet.getEleTempletSourceList().add(bgSource);
		
		EleSourceBackground esbg = eleTemplet.getBackground();
		if(!StringUtils.isEmpty(esbg.getBgGif())){
			System.out.println("111111111111111111111");
			File esbgGifFile = new File(filePath+esbg.getBgGif());

			bgFiles.add(esbgGifFile);
			String gif = esbg.getBgGif();
			gif = gif.substring(gif.lastIndexOf("/")+1, gif.length());
			esbg.setBgGif(esbgGifFile.getName());
		}
		if(!StringUtils.isEmpty(esbg.getBgImage())){
			System.out.println("2222222222222222222222");
			File esbgBgFile = new File(filePath+esbg.getBgImage());

			bgFiles.add(esbgBgFile);
			String image = esbg.getBgImage();
			image = image.substring(image.lastIndexOf("/")+1, image.length());
			esbg.setBgImage(esbgBgFile.getName());
		}
		if(!StringUtils.isEmpty(esbg.getColor())) {
		esbg.setColor(esbg.getColor().replace("#",""));
		}
		bgConfigContent = JaxbMapper.toXml(esbg, encoding);
		bgConfig = new File(configName);
		FileUtils.writeStringToFile(bgConfig, bgConfigContent,encoding, false);
		bgFiles.add(bgConfig);
		fileMap.put("background", bgFiles);
		
		//生成模板文件
		String templateId = eleTemplet.getId();
		EleSourceFont est = eleSourceFontService.get(eleTemplet.getFont().getId());

		String fontFile = filePath + est.getFont();
		String fontName = est.getFont();
		File font = new File(fontFile);

		if(fontName != null){
			fontName = fontName.substring(fontName.lastIndexOf("/") + 1, fontName.length());
            eleTemplet.setFont(new EleSourceFont("", "font/"+font.getName()));
		}

		
		List<File> fonts = new ArrayList<File>();
		fonts.add(font);
		fileMap.put("font", fonts);
		
		String destPath = basePath + "/theme/conf/"+templateId+"/theme.xml";
		System.out.println(destPath+"8888888888888888888888888888888888888888");
		String eleTempletXML = eleTempletPublishService.eleTempletToXml(eleTemplet);
		System.out.println(eleTempletXML);
		File theme = new File(destPath);
		FileUtils.writeStringToFile(theme, eleTempletXML,encoding, false);
		List<File> themes = new ArrayList<>();
		themes.add(theme);
		fileMap.put("theme", themes);
    
		String zipPath = basePath + "/theme/source/"+templateId+"/";
		String zipName = templateId + ".zip";	
		
		return zipFiles(zipPath,zipName,fileMap);
    }
    
    public Map<String,List<File>> getTemplateConfigMap(EleTemplet eleTemplet,String basePath) throws IOException{
    	    	List<EleTempletSource> templetSourceList = eleTemplet.getEleTempletSourceList();
    			String filePath = basePath.substring(0,basePath.lastIndexOf("\\elevator\\"))+"/";//basePath.replace("\\elevator\\","");
    			String encoding = "UTF-8";

    			Map<String,List<File>> fileMap = new HashMap<>();
    			for(EleTempletSource ets:templetSourceList){
    				String type = ets.getSourceType();
    				if(type == null){
    					continue;
    				}
    				List<File> files = new ArrayList<File>();
    				String configName = type+".xml";
    				File config = null;
    				String configContent = "";
    				if(type.equals("title") || type.equals("sub") || type.equals("multimedia")) {
    					continue;
    				}
    				switch(type){
    				case "direction":
    					EleSourceDirectionGroup esdg = eleSourceDirectionGroupService.get(ets.getResourceId());
    					if(esdg.getStop() != null){
    						files.add(new File(filePath+esdg.getStop()));
    						String stop = esdg.getStop();
    						stop = stop.substring(stop.lastIndexOf("/")+1, stop.length());
    						esdg.setStop(stop);
    					}
    					if(esdg.getUptips() != null){
    						files.add(new File(filePath+esdg.getUptips()));
    						String uptips = esdg.getUptips();
    						uptips = uptips.substring(uptips.lastIndexOf("/")+1, uptips.length());
    						esdg.setUptips(uptips);
    					}
    					if(esdg.getUpstop() != null){
    						files.add(new File(filePath+esdg.getUpstop()));
    						String upstop = esdg.getUpstop();
    						upstop = upstop.substring(upstop.lastIndexOf("/")+1, upstop.length());
    						esdg.setUpstop(upstop);
    					}
    					if(esdg.getDeftips()!= null){
    						files.add(new File(filePath+esdg.getDeftips()));
    						String deftips = esdg.getDeftips();
    						deftips = deftips.substring(deftips.lastIndexOf("/")+1, deftips.length());
    						esdg.setDeftips(deftips);
    					}
    					if(esdg.getDownstop() != null){
    						files.add(new File(filePath+esdg.getDownstop()));
    						String downstop = esdg.getDownstop();
    						downstop = downstop.substring(downstop.lastIndexOf("/")+1, downstop.length());
    						esdg.setDownstop(downstop);
    					}
    					if(esdg.getDowntips() != null){
    						files.add(new File(filePath+esdg.getDowntips()));
    						String downtips = esdg.getDowntips();
    						downtips = downtips.substring(downtips.lastIndexOf("/")+1, downtips.length());
    						esdg.setDowntips(downtips);
    					}
    					for(EleSourceDirection ed:esdg.getEleSourceDirectionList()){
    						String node = ed.getNode();
    						node = node.substring(node.lastIndexOf("/")+1, node.length());
    						ed.setNode(node);
    					}
    					esdg.devide();
    					configContent = JaxbMapper.toXml(esdg, encoding);
    					config = new File(configName);
    					FileUtils.writeStringToFile(config, configContent,encoding, false);
    					files.add(config);
    					break;
    				case "alarm":
    					EleSourceAlarmGroup esag = eleSourceAlarmGroupService.get(ets.getResourceId());
    					List<EleSourceAlarm> eaList = esag.getEleSourceAlarmList();
    					if(esag.getDefaudio() != null){
    						files.add(new File(filePath+esag.getDefaudio()));
    						
    						String def = esag.getDefaudio();
    						def = def.substring(def.lastIndexOf("/")+1, def.length());
    						esag.setDefaudio(def);
    					}
    					for(EleSourceAlarm ea:eaList){
    						files.add(new File(filePath+ea.getVolume()));
    						files.add(new File(filePath+ea.getImage()));
    						
    						String volume = ea.getVolume();
    						volume = volume.substring(volume.lastIndexOf("/")+1, volume.length());
    						ea.setVolume(volume);
    						
    						String image = ea.getImage();
    						image = image.substring(image.lastIndexOf("/")+1, image.length());
    						ea.setImage(image);
    					}
    					configContent = JaxbMapper.toXml(esag, encoding);
    					config = new File(configName);
    					FileUtils.writeStringToFile(config, configContent,encoding, false);
    					files.add(config);
    					break;
    				case "date":
    					EleSourceDate esd = eleSourceDateService.get(ets.getResourceId());
    					esd.setFgcolor(ColorUtils.rgba2rgb(esd.getFgcolor()));
    					esd.setBgcolor(esd.getBgcolor().replace("#",""));

    					configContent = JaxbMapper.toXml(esd, encoding);
    					config = new File(configName);
    					FileUtils.writeStringToFile(config, configContent,encoding, false);
    					files.add(config);
    					break;
    				case "time":
    					EleSourceTime estime = eleSourceTimeService.get(ets.getResourceId());
    					estime.setFgcolor(ColorUtils.rgba2rgb(estime.getFgcolor()));
    					estime.setBgcolor(estime.getBgcolor().replace("#",""));

    					configContent = JaxbMapper.toXml(estime, encoding);
    					config = new File(configName);
    					FileUtils.writeStringToFile(config, configContent,encoding, false);
    					files.add(config);
    					break;
    				case "weather":
    					EleSourceWeather esw = eleSourceWeatherService.get(ets.getResourceId());
    					esw.setFgcolor(ColorUtils.rgba2rgb(esw.getFgcolor()));
    					esw.setBgcolor(esw.getBgcolor().replace("#",""));

    					configContent = JaxbMapper.toXml(esw, encoding);
    					config = new File(configName);
    					System.out.println(config.getAbsolutePath());
    					FileUtils.writeStringToFile(config, configContent,encoding, false);
    					files.add(config);
    					break;
    				case "logo":
    					EleSourceLogo logo = eleSourceLogoService.get(ets.getResourceId());
    					configContent = JaxbMapper.toXml(logo, encoding);
    					config = new File(configName);
    					System.out.println(config.getAbsolutePath());
    					FileUtils.writeStringToFile(config, configContent,encoding, false);
    					files.add(config);
    					break;
    				case "week":
    					EleSourceWeek esweek = eleSourceWeekService.get(ets.getResourceId());
    					esweek.setFgcolor(ColorUtils.rgba2rgb(esweek.getFgcolor()));
    					esweek.setBgcolor(esweek.getBgcolor().replace("#",""));

    					configContent = JaxbMapper.toXml(esweek, encoding);
    					config = new File(configName);
    					FileUtils.writeStringToFile(config, configContent,encoding, false);
    					files.add(config);
    					break;
    				case "floor":
    					EleSourceFloor esfloor = eleSourceFloorService.get(ets.getResourceId());
    					esfloor.setFloornodes(floorNodeService.getByGroupId(esfloor.getId()));
    					if(esfloor.getVolumeSelect() != null){
    						String volume = esfloor.getVolumeSelect();
    						files.add(new File(filePath+esfloor.getVolumeSelect()));
    						volume = volume.substring(volume.lastIndexOf("/")+1, volume.length());
    						esfloor.setVolumeSelect(volume);
    					}
    					for(FloorNode f:esfloor.getFloornodes()){
    						if(f.getFloorimg() != null){
    							String image = f.getFloorimg();
    							files.add(new File(filePath+f.getFloorimg()));
    							image = image.substring(image.lastIndexOf("/")+1, image.length());
    							f.setFloorimg(image);
    						}
    					}
    					for(Floor f:esfloor.getFloors()){
    						if(f.getVolumeCn() != null){
    							String volume = f.getVolumeCn();
    							files.add(new File(filePath+f.getVolumeCn()));
    							volume = volume.substring(volume.lastIndexOf("/")+1, volume.length());
    							f.setVolumeCn(volume);;
    						}
    						if(f.getVolumeEn() != null){
    							String volume = f.getVolumeEn();
    							files.add(new File(filePath+f.getVolumeEn()));
    							volume = volume.substring(volume.lastIndexOf("/")+1, volume.length());
    							f.setVolumeEn(volume);
    						}
    					}
    					configContent = JaxbMapper.toXml(esfloor, encoding).replaceAll("<floorimg>","").replaceAll("</floorimg>","");
    					config = new File(configName);
    					FileUtils.writeStringToFile(config, configContent,encoding, false);
    					files.add(config);
    					break;
					case "floored":
    				case "registerfloor":
    					EleSourceFloored esfloored = eleSourceFlooredService.get(ets.getResourceId());
    					esfloored.setFgcolor(ColorUtils.rgba2rgb(esfloored.getFgcolor()));
    					esfloored.setBgcolor(esfloored.getBgcolor().replace("#",""));
    					configContent = JaxbMapper.toXml(esfloored, encoding);
    					config = new File(configName);
    					FileUtils.writeStringToFile(config, configContent,encoding, false);
    					files.add(config);
    					break;
    				default:
    					break;
    				}
    				
    				fileMap.put(type, files);
    				System.out.println(configContent);
    			}
    			
    			//单独处理模板背景
    			List<File> bgFiles = new ArrayList<File>();
    			String configName = "background.xml";
    			File bgConfig = null;
    			String bgConfigContent = "";
    			
    			EleTempletSource bgSource = new EleTempletSource();
    			bgSource.setCfgfile(configName);
    			bgSource.setRespath("background");
    			bgSource.setXloc("0");
    			bgSource.setYloc("0");
    			bgSource.setWidth(eleTemplet.getWidth()+"");
    			bgSource.setHeight(eleTemplet.getHeight()+"");
    			bgSource.setSourceType("background");
    			eleTemplet.getEleTempletSourceList().add(bgSource);
    			
    			EleSourceBackground esbg = eleTemplet.getBackground();
    			if(!StringUtils.isEmpty(esbg.getBgGif())){
    				System.out.println("111111111111111111111");
    				bgFiles.add(new File(filePath+esbg.getBgGif()));
    				String gif = esbg.getBgGif();
    				gif = gif.substring(gif.lastIndexOf("/")+1, gif.length());
    				esbg.setBgGif(gif);
    			}
    			if(!StringUtils.isEmpty(esbg.getBgImage())){
    				System.out.println("2222222222222222222222");

    				bgFiles.add(new File(filePath+esbg.getBgImage()));
    				String image = esbg.getBgImage();
    				image = image.substring(image.lastIndexOf("/")+1, image.length());
    				esbg.setBgImage(image);
    			}
    			esbg.setColor(esbg.getColor().replace("#",""));
    			bgConfigContent = JaxbMapper.toXml(esbg, encoding);
    			bgConfig = new File(configName);
    			FileUtils.writeStringToFile(bgConfig, bgConfigContent,encoding, false);
    			bgFiles.add(bgConfig);
    			fileMap.put("background", bgFiles);
    			
    			//生成模板文件
    			String templateId = eleTemplet.getId();
    			EleSourceFont est = eleSourceFontService.get(eleTemplet.getFont().getId());

    			String fontFile = filePath + est.getFont();
    			String fontName = est.getFont();
    			if(fontName != null){
    				fontName = fontName.substring(fontName.lastIndexOf("/") + 1, fontName.length());
    	            eleTemplet.setFont(new EleSourceFont("", "font/"+fontName));
    			}

    			File font = new File(fontFile);
    			List<File> fonts = new ArrayList<File>();
    			fonts.add(font);
    			fileMap.put("font", fonts);
    			
    			String destPath = basePath + "/theme/conf/"+templateId+"/theme.xml";
    			System.out.println(destPath+"8888888888888888888888888888888888888888");
    			String eleTempletXML = eleTempletPublishService.eleTempletToXml(eleTemplet);
    			File theme = new File(destPath);
    			FileUtils.writeStringToFile(theme, eleTempletXML,encoding, false);
    			List<File> themes = new ArrayList<>();
    			themes.add(theme);
    			fileMap.put("theme", themes);
    			return fileMap;
    }

	public boolean zipFiles(String zipPath, String zipName, Map<String, List<File>> map){
		File tmpZipFile = null;
		ZipOutputStream out = null;
		FileInputStream fis = null;
		try{
			// String tmpFileName = "report.zip";
			byte[] buffer = new byte[1024];
			// String strZipPath =
			// COM_REPORT_PATH+"/"+user.getOid()+"/"+report.getOid()+"/"+tmpFileName;

			String strZipPath = zipPath + "/" + zipName;
			File tmpZip = new File(zipPath);
			if(!tmpZip.exists())
				tmpZip.mkdirs();
			tmpZipFile = new File(strZipPath);
			if(!tmpZipFile.exists())
				tmpZipFile.createNewFile();

			out = new ZipOutputStream(new FileOutputStream(strZipPath));
			Set<String> keys = map.keySet();
			for(String key : keys){
				List<File> files = map.get(key);
				String dir = key + "/";
				if(key.equals("theme") || key.equals("program")){
					dir = "/";
				}
				//增加外部文件夹
				out.putNextEntry(new ZipEntry(dir));
				System.out.println(key);
				System.out.println(files.size());
				for(int i = 0; i < files.size(); i++){
					File f = files.get(i);
					System.out.println(f.getName());
					if(f.isDirectory()){
						continue;
					}
					fis = new FileInputStream(f);
					out.putNextEntry(new ZipEntry(dir + files.get(i).getName()));
					// 设置压缩文件内的字符编码，不然会变成乱码
					out.setEncoding("UTF-8");
					int len;
					// 读入需要下载的文件的内容，打包到zip文件
					while((len = fis.read(buffer)) > 0){
						out.write(buffer, 0, len);
					}
					out.closeEntry();
					fis.close();
				}
				out.closeEntry();
			}
			out.close();
			return true;

		}
		catch(Exception e){
			if(fis != null) {
				try{
					fis.close();
				} catch(Exception ex) {

				}
			}
			if(out != null) {
				try{
					out.closeEntry();
				} catch(Exception ex) {

				}
				try{
					out.close();
				} catch(Exception ex) {

				}
			}
			if(tmpZipFile!= null && tmpZipFile.exists())
				tmpZipFile.delete();
			logger.error("生成zip文件失败!", e);
			return false;
		}
	}

	public boolean processImportTemplate(String templateName,String filePath,EleTemplet tmp) throws IOException {
	    String basePath = Global.getUserfilesBaseDir();
	    System.out.println(basePath+"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");

	    String fileBasePath = basePath.substring(0,basePath.lastIndexOf("\\elevator\\"))+"/";//basePath.replace("\\elevator\\","");
		String filePathPrefix = fileBasePath;
		
		String dirPath = fileBasePath+FileUtils.getFileNameWithoutExtension(filePath);
		
		System.out.println(dirPath);
		FileUtils.unZipFiles(fileBasePath+filePath, dirPath);
		String encoding = "UTF-8";
		File dir = new File(dirPath);
		File[] files = dir.listFiles();
		File themeFile = null;
		File fontFile = null;
		EleSourceBackground esbg = null;
		Map<String,JSONObject> resources = new HashMap<String,JSONObject>();
		for(File file:files) {
			if(file.isFile()) {
				themeFile = file;
			}
			if(file.isDirectory() && file.getName().equals("font")) {
				File[] fonts = file.listFiles();
				if(fonts.length != 1) {
					return false;
				}
				fontFile = fonts[0];
			}
			if(file.isDirectory() && !(file.getName().equals("font"))) {
				String type = file.getName();
				String xmlDir = dirPath +"/" + file.getName()+ "/";
				String xmlPath = xmlDir + file.getName()+".xml";
				System.out.println(xmlPath);

				File config = new File(xmlPath);
				String configContent = FileUtils.readFileToString(config, encoding); 
				System.out.println(configContent);
				switch(type){
				case "title":
					EleSourceTitle est = JaxbMapper.fromXml(configContent, EleSourceTitle.class);
					est.setBgcolor("#"+est.getBgcolor());
					est.setFgcolor("#"+est.getFgcolor());
					est.setName(templateName);
					
					eleSourceTitleService.save(est);
					
					String titleGroupId = createPackageForImportedSource(est.getId(), est.getName(),"title");
					eleSourceTitleService.updateGroupId(titleGroupId, est.getId());
					JSONObject jsonTitle = new JSONObject();
					jsonTitle.put("id", est.getId());
					jsonTitle.put("name", est.getName());
					resources.put("title", jsonTitle);
					break;
				case "sub":
					EleSourceSubtitleGroup essg = JaxbMapper.fromXml(configContent, EleSourceSubtitleGroup.class);
					essg.setName(templateName);
					if(!StringUtils.isEmpty(essg.getBgimage())) {
						String bgimage = xmlDir + essg.getBgimage();
						essg.setBgimage(bgimage.replace(filePathPrefix, ""));
					}
					for(EleSourceSubtitle ess :essg.getEleSourceSubtitleList()) {
						ess.setId("");
					}
					eleSourceSubtitleGroupService.save(essg);
					String subGroupId = createPackageForImportedSource(essg.getId(),essg.getName(),"subtitle");
					eleSourceSubtitleGroupService.updateGroupId(subGroupId, essg.getId());
					JSONObject jsonSub = new JSONObject();
					jsonSub.put("id", essg.getId());
					jsonSub.put("name", essg.getName());
					resources.put("sub", jsonSub);
					break;
				case "multimedia":
					EleSourceMultimedia em = JaxbMapper.fromXml(configContent, EleSourceMultimedia.class);
					em.setName(templateName);
					if("video".equals(em.getType())) {
						EleSourceVideoGroup videoGroup = em.getVideoGroup();
						for(EleSourceVideo esv:videoGroup.getEleSourceVideoList()) {
								esv.setId("");
								if(!StringUtils.isEmpty(esv.getPath())) {
									String videoPath = xmlDir + esv.getPath();
									esv.setPath(videoPath.replace(filePathPrefix, ""));
								}
						}
					}else if("image".equals(em.getType())) {
						EleSourceImageGroup imageGroup = em.getImageGroup();
						for(EleSourceImage esi:imageGroup.getEleSourceImageList()) {
							esi.setId("");
							if(!StringUtils.isEmpty(esi.getPath())) {
								String imagePath = xmlDir + esi.getPath();
								esi.setPath(imagePath.replace(filePathPrefix, ""));
							}
						}
					}
					eleSourceMultimediaService.save(em);
					String mediaGroupId = createPackageForImportedSource(em.getId(),em.getName(),"multimedia");
					eleSourceMultimediaService.updateGroupId(mediaGroupId, em.getId());
					JSONObject jsonMultimedia = new JSONObject();
					jsonMultimedia.put("id", em.getId());
					jsonMultimedia.put("name", em.getName());
					resources.put("multimedia", jsonMultimedia);
					break;
					
				case "direction":
					EleSourceDirectionGroup esdg = JaxbMapper.fromXml(configContent, EleSourceDirectionGroup.class);
					esdg.setName(templateName);
					if(!StringUtils.isEmpty(esdg.getDeftips())) {
						String defTips = xmlDir + esdg.getDeftips();
						esdg.setDeftips(defTips.replace(filePathPrefix, ""));
					}
					if(!StringUtils.isEmpty(esdg.getStop())) {
						String stop = xmlDir + esdg.getStop();
						esdg.setStop(stop.replace(filePathPrefix, ""));
					}
					if(!StringUtils.isEmpty(esdg.getUpstop())) {
						String upStop = xmlDir + esdg.getUpstop();
						esdg.setUpstop(upStop.replace(filePathPrefix, ""));
					}
					if(!StringUtils.isEmpty(esdg.getUptips())) {
						String upTips = xmlDir + esdg.getUptips();
						esdg.setUptips(upTips.replace(filePathPrefix, ""));
					}
					if(!StringUtils.isEmpty(esdg.getDownstop())) {
						String downStop = xmlDir + esdg.getDownstop();
						esdg.setDownstop(downStop.replace(filePathPrefix, ""));
					}
					if(!StringUtils.isEmpty(esdg.getDowntips())) {
						String downTips = xmlDir + esdg.getDowntips();
						esdg.setDowntips(downTips.replace(filePathPrefix, ""));
					}
					 List<String> upnodes = esdg.getUpnodes();
					 for(String eld:upnodes) {
						 EleSourceDirection ed = new EleSourceDirection();
						 ed.setDirection("up");
						 String node = xmlDir + eld;
						 ed.setNode(node.replace(filePathPrefix, ""));
						 ed.setId("");
						 esdg.getEleSourceDirectionList().add(ed);
					 }
					 
					 List<String> downnodes = esdg.getDownnodes();
					 for(String eld:downnodes) {
						 EleSourceDirection ed = new EleSourceDirection();
						 ed.setDirection("down");
						 String node = xmlDir + eld;
						 ed.setNode(node.replace(filePathPrefix, ""));
						 ed.setId("");
						 esdg.getEleSourceDirectionList().add(ed);
					 }
					 System.out.println(esdg.getEleSourceDirectionList().size());
					eleSourceDirectionGroupService.save(esdg);
					System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>sadsadsadsadsa");
					JSONObject jsonDirection = new JSONObject();
					jsonDirection.put("id", esdg.getId());
					jsonDirection.put("name", esdg.getName());
					resources.put("direction", jsonDirection);
					
					break;
				case "alarm":
					EleSourceAlarmGroup esag = JaxbMapper.fromXml(configContent, EleSourceAlarmGroup.class);
					esag.setName(templateName);
					if(!StringUtils.isEmpty(esag.getDefaudio())) {
						String defAudio = xmlDir + esag.getDefaudio();
						esag.setDefaudio(defAudio.replace(filePathPrefix, ""));
					}
					List<EleSourceAlarm> eaList = esag.getEleSourceAlarmList();

					for(EleSourceAlarm alarm : eaList) {
						if(!StringUtils.isEmpty(alarm.getImage())) {
							String alarmImage = xmlDir + alarm.getImage();
							alarm.setImage(alarmImage.replace(filePathPrefix, ""));
						}
						if(!StringUtils.isEmpty(alarm.getVolume())) {
							String alarmVolume = xmlDir + alarm.getVolume();
							alarm.setVolume(alarmVolume.replace(filePathPrefix, ""));
						}
						if(!StringUtils.isEmpty(alarm.getImageCn())) {
							String alarmImageCn = xmlDir + alarm.getImageCn();
							alarm.setImageCn(alarmImageCn.replace(filePathPrefix, ""));
						}
						alarm.setGroup(esag);
						alarm.setId("");
					}
					eleSourceAlarmGroupService.save(esag);
					
					JSONObject jsonAlarm = new JSONObject();
					jsonAlarm.put("id", esag.getId());
					jsonAlarm.put("name", esag.getName());
					resources.put("alarm", jsonAlarm);
					break;
				case "date":
					EleSourceDate esd = JaxbMapper.fromXml(configContent, EleSourceDate.class);
					//esd.setArea("false");
					esd.setFgcolor("#"+esd.getFgcolor());
					esd.setName(templateName);
					eleSourceDateService.save(esd);

					JSONObject jsonDate = new JSONObject();
					jsonDate.put("id", esd.getId());
					jsonDate.put("name", esd.getName());
					resources.put("date", jsonDate);
					break;
				case "time":
					EleSourceTime estime = JaxbMapper.fromXml(configContent, EleSourceTime.class);
					estime.setFgcolor("#"+estime.getFgcolor());
					estime.setName(templateName);
					eleSourceTimeService.save(estime);
					
					JSONObject jsonTime = new JSONObject();
					jsonTime.put("id", estime.getId());
					jsonTime.put("name", estime.getName());
					resources.put("time", jsonTime);

					break;
				case "weather":
					EleSourceWeather esw = JaxbMapper.fromXml(configContent, EleSourceWeather.class);
					esw.setFgcolor("#"+esw.getFgcolor());
					esw.setName(templateName);
					eleSourceWeatherService.save(esw);
					
					JSONObject jsonWeather = new JSONObject();
					jsonWeather.put("id", esw.getId());
					jsonWeather.put("name", esw.getName());
					resources.put("weather", jsonWeather);
					break;
				case "logo":
					EleSourceLogo logo = JaxbMapper.fromXml(configContent, EleSourceLogo.class);
					logo.setName(templateName);
					if(!StringUtils.isEmpty(logo.getPath())){
						String logoPath = xmlDir + logo.getPath();
						logo.setPath(logoPath.replace(filePathPrefix, ""));
					}
					eleSourceLogoService.save(logo);
					
					JSONObject jsonLogo = new JSONObject();
					jsonLogo.put("id", logo.getId());
					jsonLogo.put("name", logo.getName());
					resources.put("logo", jsonLogo);
					break;
				case "week":
					EleSourceWeek esweek = JaxbMapper.fromXml(configContent, EleSourceWeek.class);
					esweek.setFgcolor("#"+esweek.getFgcolor());
					esweek.setName(templateName);
					eleSourceWeekService.save(esweek);
					
					JSONObject jsonWeek = new JSONObject();
					jsonWeek.put("id", esweek.getId());
					jsonWeek.put("name", esweek.getName());
					resources.put("week", jsonWeek);

					break;
				case "background":
					esbg = JaxbMapper.fromXml(configContent, EleSourceBackground.class);
					if(!StringUtils.isEmpty(esbg.getColor())) {
						esbg.setColor("#"+esbg.getColor());
					}
					if(!StringUtils.isEmpty(esbg.getBgImage())) {
					String bgImage = xmlDir + esbg.getBgImage();
					esbg.setBgImage(bgImage.replace(filePathPrefix, ""));
					}
					if(!StringUtils.isEmpty(esbg.getBgGif())) {
					String bgGif = xmlDir + esbg.getBgGif();
					esbg.setBgGif(bgGif.replace(filePathPrefix, ""));
					}
					break;
				case "floor":
					EleSourceFloor floor = JaxbMapper.fromXml(configContent, EleSourceFloor.class);
					floor.setName(templateName);
					List<Floor> floors = floor.getFloors();
					for(Floor f:floors) {
						f.setId("");
						if(!StringUtils.isEmpty(f.getVolumeCn())) {
							String volumeCn = xmlDir + f.getVolumeCn();
							f.setVolumeCn(volumeCn.replace(filePathPrefix, ""));
						}
						if(!StringUtils.isEmpty(f.getVolumeEn())) {
							String volumeEn = xmlDir + f.getVolumeEn();
							f.setVolumeEn(volumeEn.replace(filePathPrefix, ""));
						}
					}
					List<FloorNode> floorNodes = Lists.newArrayList();
					List<FloorNode> nodes = floor.getFloornodes();
					if(nodes.size() > 0) {
						org.json.JSONObject xmlJSONObj=XML.toJSONObject(configContent);
						JSONObject data = JSONObject.parseObject(xmlJSONObj.toString(4));
						JSONObject floornodes = data.getJSONObject("floorcfg").getJSONObject("floornodes");
						JSONArray array = floornodes.getJSONArray("node");
						for(int i=0;i<array.size();i++) {
							JSONObject node = array.getJSONObject(i);
							FloorNode fn = new FloorNode();
							fn.setId("");
							fn.setFloorId(node.getString("id"));

							if(!StringUtils.isEmpty(node.getString("content"))) {
								String nodeImage = xmlDir + node.getString("content");
								fn.setFloorimg(nodeImage.replace(filePathPrefix, ""));
							}
							floorNodes.add(fn);
						}
					}
					floor.setFloornodes(floorNodes);
					eleSourceFloorService.save(floor);
					
					JSONObject jsonFloor = new JSONObject();
					jsonFloor.put("id", floor.getId());
					jsonFloor.put("name", floor.getName());
					resources.put("floor", jsonFloor);
					
					break;

				case "floored":
				case "registerfloor":
					EleSourceFloored esFloored = JaxbMapper.fromXml(configContent, EleSourceFloored.class);
					esFloored.setBgcolor("#"+esFloored.getBgcolor());
					esFloored.setFgcolor("#"+esFloored.getFgcolor());
					esFloored.setName(templateName);
					eleSourceFlooredService.save(esFloored);
					
					JSONObject jsonFloored = new JSONObject();
					jsonFloored.put("id", esFloored.getId());
					jsonFloored.put("name", esFloored.getName());
					resources.put("registerfloor", jsonFloored);
					
					break;
				default:
					break;
				}
			}
		}
		if(themeFile == null) {
			return false;
		}
		String themeContent = FileUtils.readFileToString(themeFile, encoding);
		EleTemplet eleTemplet =  JaxbMapper.fromXml(themeContent, EleTemplet.class);
		System.out.println("------------------"+eleTemplet.getDisplaymode());
		System.out.println("-----------------"+DictUtils.getEnDictValue(eleTemplet.getDisplaymode(), "orientation", "1"));
		eleTemplet.setDisplaymode(DictUtils.getEnDictValue(eleTemplet.getDisplaymode(), "orientation", "1"));
		for(EleTempletSource ets : eleTemplet.getEleTempletSourceList()) {
			System.out.println(ets.getSourceType());
			if(!(ets.getSourceType().equals("background") )){
				ets.setId("");
				ets.setTemplet(eleTemplet);
				ets.setResourceId(resources.get(ets.getSourceType()).getString("id"));
				ets.setResourceName(resources.get(ets.getSourceType()).getString("name"));
				if(ets.getSourceType().equals("registerfloor")){
					ets.setSourceType("floored");
				}
			}
		}		
		
		EleSourceFont font = new EleSourceFont();
		font.setName(templateName);
		System.out.println(fontFile.getAbsolutePath()+">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
		System.out.println(fileBasePath+">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
		System.out.println(fontFile.getAbsolutePath().replace(filePathPrefix, ""));

		font.setFont(fontFile.getAbsolutePath().replace(filePathPrefix.substring(0, filePathPrefix.length()-1), ""));
		eleSourceFontService.save(font);
		
		eleTemplet.setName(templateName);
		eleTemplet.setFont(font);
		eleTemplet.setWidth(Integer.parseInt(eleTemplet.getResolutionStr().split("x")[0]));
		eleTemplet.setHeight(Integer.parseInt(eleTemplet.getResolutionStr().split("x")[1]));

		if(esbg != null) {
			eleTemplet.setBackground(esbg);
		}
		save(eleTemplet,null);
		tmp.setId(eleTemplet.getId());
		return true;
	}
	
	private String createPackageForImportedSource(String sourceId,String sourceName,String type) {
		EleSourceGroup eleSourceGroup = null;
		eleSourceGroup = new EleSourceGroup();
		EleSource source = new EleSource();
		source.setId("");
		source.setType(type);
		source.setName(type+"Generated");
		source.setContent(sourceId);
			
		List<EleSource> esList = Lists.newArrayList();
		esList.add(source);
		eleSourceGroup.setEleSourceList(esList);
		eleSourceGroup.setVisible("0");
		eleSourceGroup.setType(type);
		eleSourceGroup.setDelFlag(EleSourceGroup.DEL_FLAG_NORMAL);

		eleSourceGroup.setName(sourceName);

		eleSourceGroupService.save(eleSourceGroup);
		String basePath = Global.getUserfilesBaseDir();
		try {
			createPackageForSourceGroup(eleSourceGroup, basePath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return eleSourceGroup.getId();
	}
	public void createPackageForProgramSourceGroup(EleSourceGroup eleSourceGroup,String basePath){
		List<EleSource> esList = eleSourceGroup.getEleSourceList();
		String egId = eleSourceGroup.getId();
		
		String filePath = basePath.substring(0,basePath.lastIndexOf("\\elevator\\"))+"/";//basePath.replace("\\elevator\\","");
		if(esList.isEmpty()){
			return;
		}
		EleSource tmp = esList.get(0);
		EleSourceProgram esp = eleSourceProgramService.get(tmp.getContent());
		String zipPath = basePath + "/theme/source/"+egId+"/";
		String zipName = egId + ".zip";	
		
		Map<String,List<File>> fileMap = new HashMap<>();
		List<File> files = new ArrayList<File>();
		files.add(new File(filePath + esp.getPath()));
		fileMap.put("program", files);
		zipFiles(zipPath, zipName, fileMap);
	}
	public boolean createPackageForSourceGroup(EleSourceGroup eleSourceGroup,String basePath) throws IOException{
		List<EleSource> esList = eleSourceGroup.getEleSourceList();
		String egId = eleSourceGroup.getId();
		String encoding = "UTF-8";
	
		String filePath = basePath.substring(0,basePath.lastIndexOf("\\elevator\\"))+"/";//basePath.replace("\\elevator\\","");
		Map<String,List<File>> fileMap = new HashMap<>();
		for(EleSource es:esList){
			String type = es.getType();
			if(type == null){
				continue;
			}
			List<File> files = new ArrayList<File>();
			String configName = type+".xml";
			File config = null;
			String configContent = "";
			switch(type){
			case "multimedia":
				EleSourceMultimedia eleSourceMultimedia = eleSourceMultimediaService.get(es.getContent());
				String videoId = eleSourceMultimedia.getVideoId();
				String imageId = eleSourceMultimedia.getImageId();
				if (!StringUtils.isEmpty(videoId)) {
					EleSourceVideoGroup esvg = eleSourceVideoGroupService.get(videoId);
					List<EleSourceVideo> esvList = esvg.getEleSourceVideoList();
					for (EleSourceVideo esv : esvList) {
						System.out.println(esv.getPath());
						files.add(new File(filePath + esv.getPath()));
						String path = esv.getPath();
						path = path.substring(path.lastIndexOf("/") + 1, path.length());
						esv.setPath(path);
					}
					eleSourceMultimedia.setVideoGroup(esvg);
				}
				if (!StringUtils.isEmpty(imageId)) {
					EleSourceImageGroup esig = eleSourceImageGroupService.get(imageId);
					List<EleSourceImage> esiList = esig.getEleSourceImageList();
					for (EleSourceImage esi : esiList) {
						files.add(new File(filePath + esi.getPath()));
						String path = esi.getPath();
						path = path.substring(path.lastIndexOf("/") + 1, path.length());
						esi.setPath(path);
					}
					eleSourceMultimedia.setImageGroup(esig);
				}
				configContent = JaxbMapper.toXml(eleSourceMultimedia, encoding);
				config = new File(configName);
				FileUtils.writeStringToFile(config, configContent,encoding, false);
				files.add(config);
				break;
			case "subtitle":
				EleSourceSubtitleGroup essg = eleSourceSubtitleGroupService.get(es.getContent());
				if(!StringUtils.isEmpty(essg.getBgimage())){
					files.add(new File(filePath+essg.getBgimage()));
					String image = essg.getBgimage();
					image = image.substring(image.lastIndexOf("/")+1, image.length());
					essg.setBgimage(image);
				}
				essg.setBgcolor(essg.getBgcolor().replace("#", ""));
				essg.setFgcolor(ColorUtils.rgba2rgb(essg.getFgcolor()));
				configContent = JaxbMapper.toXml(essg, encoding);
				configName = "sub.xml";
				type = "sub";
				config = new File(configName);
				FileUtils.writeStringToFile(config, configContent,encoding, false);
				files.add(config);
				break;
			case "title":
				EleSourceTitle est = eleSourceTitleService.get(es.getContent());
				est.setBgcolor(est.getBgcolor().replace("#", ""));
				est.setFgcolor(ColorUtils.rgba2rgb(est.getFgcolor()));
				configContent = JaxbMapper.toXml(est, encoding);
				config = new File(configName);
				FileUtils.writeStringToFile(config, configContent,encoding, false);
				files.add(config);
				break;
		
			default:
				break;
			}
			fileMap.put(type, files);
			System.out.println(configContent);
		}
		
		String zipPath = basePath + "/theme/source/"+egId+"/";
		String zipName = egId + ".zip";	
		if(eleSourceGroup.getTemplet() != null && !StringUtils.isEmpty(eleSourceGroup.getTemplet().getId())){
			String templateId = eleSourceGroup.getTemplet().getId();
			
			EleTemplet eleTemplet = get(templateId);


			EleSourceFont est = eleTemplet.getFont();

			String fontFile = filePath + est.getFont();
			String fontName = est.getFont();
			if(fontName != null){
				fontName = fontName.substring(fontName.lastIndexOf("/") + 1, fontName.length());
	            eleTemplet.setFont(new EleSourceFont("", "font/"+fontName));
			}

			File font = new File(fontFile);
			List<File> fonts = new ArrayList<File>();
			fonts.add(font);
			fileMap.put("font", fonts);
			
			String destPath = basePath + "/theme/conf/"+templateId+"/theme.xml";
			String eleTempletXML = eleTempletPublishService.eleTempletToXml(eleTemplet);
			File theme = new File(destPath);
			FileUtils.writeStringToFile(theme, eleTempletXML,encoding, false);
			List<File> themes = new ArrayList<>();
			themes.add(theme);
			fileMap.put("theme", themes);
			
		}
		return zipFiles(zipPath,zipName,fileMap);

	}
	
}